<template>
  <div class="sub-out ">
    <proTable class="bg_style " @rowData="handleRowData" :loading="page.tableLoad" :columns="page.columns"
      :data="page.data" @clickPage="onClickPage" :current="pege_param.start_recd" :total="page.allTotal"
      :pageSize="pege_param.limit_recd">
    </proTable>
    <pro-dialog class="setdialog" ref="addqxgz" width="628" :nopadding="true"
      :title="`${flawTypeflag ? '新增' : '编辑'}规则`">
      <div style="padding: 32px 50px 32px 40px">
        <YsForm ref="heiduForm" :model="ruleInfo" :label-width="120" :rules="app_rule">
          <YsRow :gutter="16">
            <YsCol span="24">
              <YsFormItem label="规则名称" prop="rule_name">
                <YsInput size="large" maxlength="100" v-model="ruleInfo.rule_name"></YsInput>
              </YsFormItem>
            </YsCol>
          </YsRow>
          <YsRow :gutter="16">
            <YsCol span="24">
              <YsFormItem label="像素距离(um)" prop="pixel">
                <YsInput size="large" type="number" :maxlength="50" v-model.number="ruleInfo.pixel"></YsInput>
              </YsFormItem>
            </YsCol>
          </YsRow>
          <YsRow :gutter="16">
            <YsCol span="24">
              <YsFormItem label="标准片" prop="rule_file_name">
                <YsUpload :action="fileupload.uploadpath" ref="upload" v-if="uploadFlag"
                  :on-exceeded-size="handleMaxSize" :before-upload="uploadProcessThen"
                  :on-success="(res, file, fileList) => handleSuccess(res, file, fileList, fileupload.upload_path)"
                  :on-format-error="handleFormatError" class="demo-upload-all border_style">
                  <span>{{ fileupload.upload_name }}</span>
                  <div class="demo-upload-add">
                    <YsIcon type="ios-camera" size="20"></YsIcon>
                  </div>
                </YsUpload>
              </YsFormItem>
            </YsCol>
          </YsRow>
          <YsRow :gutter="16">
            <YsCol span="24">
              <YsFormItem label="备注">
                <YsInput size="large" type="textarea" maxlength="200" placeholder="最长可输入200字符" class="hg100"
                  v-model="ruleInfo.remark"></YsInput>
              </YsFormItem>
            </YsCol>
          </YsRow>
        </YsForm>
        <YsRow class="foot-btn" style="margin-top: 10px">
          <YsButton @click="handleCancel()" size="large">关闭</YsButton>
          <YsButton @click="handleOk('heiduForm')" :disabled="fileSuccess" size="large" type="primary">确定</YsButton>
        </YsRow>
      </div>
    </pro-dialog>
    <div class="spin_x ivu-spin ivu-spin-default ivu-spin-fix ivu-spin-show-text" v-if="spinning">
      <YsProgress class="progress" :percent="percent_val" hide-info />
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: "topHdTable",
  props: {
    rule_type: {
      type: Number,
      default: () => null
    },
    //数据
    modal_name: {
      type: String,
      default: () => null
    },
    butFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    var validateStart = (rule, value, callback) => {
      if (Number(this.ruleInfo.pixel) <= 0) {
        this.ruleInfo.pixel = null
        callback(new Error('必须大于0'));
      } else if (this.ruleInfo.pixel) {
        this.$refs.heiduForm.validateField('pixel');
      }
      callback();
    };
    var fileNameValidateStart = (rule, value, callback) => {
      if (this.ruleInfo.rule_file_name == '') {
        this.ruleInfo.pixel = ''
        callback(new Error('标准片不能为空'));
      }
      callback();
    };
    return {
      uploadFlag: true,
      fileSuccess: false,
      clearTimer: null,
      percent_val: 0,
      spinning: false,
      defaultList: [],
      fileupload: {
        type: null, //类型
        uploadpath: "", //路径
        upload_name: "", //名字
        upload_path: "",
        data: {},
        name: "",
      },
      pege_param: {
        rule_type: this.rule_type, //规则类型：6黑度检测
        keyword: "", // 查询参数：名称、编码
        start_recd: 1, //开始数据
        limit_recd: 5, //查询的条数
      },
      flawTypeflag: true,
      pre_version: "CIR",
      ruleInfo: {
        rule_name: "",//规则名称
        rule_type: this.rule_type, //规则类型
        rule_file: "", //规则文件
        rule_file_name: "",//规则文件名称
        pixel: null,
        remark: "",//备注
        rule_parts: [],//
        rule_materials: [],
        rule_craft_beans: [], //焊接方式集合
        current_parts: [],
        current_materials: [],
        current_beans: [],
      },
      page: {
        subscribeState: 0,
        tableLoad: false,
        allTotal: 0,
        columns: [
          {
            title: "序号",
            width: 80,
            tooltip: true,
            render: (h, params) => {
              return h(
                "span",
                params.index +
                (this.pege_param.start_recd - 1) *
                this.pege_param.limit_recd +
                1
              );
            },
          },
          {
            title: "状态",
            minWidth: 80,
            tooltip: true,
            key: "rule_state",
            render: (h, params) => {
              if (params.row.rule_state == '0') {
                return h('span', {}, '新建')
              }
              if (params.row.rule_state == '2') {
                return h('span', {}, '提交')
              }
              if (params.row.rule_state == '1') {
                return h('span', {}, '发布')
              }
            }
          },
          {
            title: "规则名称",
            tooltip: true,
            width: 120,
            key: "rule_name",
          },
          {
            title: "规则编号",
            width: 120,
            tooltip: true,
            key: "rule_code",
          },
          {
            title: "标准片",
            minWidth: 80,
            tooltip: true,
            key: "rule_file_name",
          },
          {
            title: "像素距离（um）",
            width: 150,
            tooltip: true,
            key: "pixel",
          },
          {
            title: "备注",
            minWidth: 80,
            key: "remark",
            tooltip: true,
          },
          {
            title: "操作",
            width: 160,
            tooltip: true,
            render: (h, params) => {
              return h(
                "div",
                {
                  attrs: { class: "mouse-on" },
                },
                [
                  h("span", {
                    domProps: {
                      innerText: '提交',
                    },
                    style: {
                      display: params.row.rule_state != 0 ? "none" : "inline-block",
                      margin: '0 6px 0 0',
                    },
                    class: "textColor",
                    on: {
                      click: (event) => {
                        this.setSubmitFn(params.row)
                        event.stopPropagation();
                      },
                    },
                  }),
                  h("span", {
                    domProps: {
                      innerText: '发布',
                    },
                    style: {
                      display: params.row.rule_state == 2 ? "inline-block" : "none",
                      margin: '0 6px 0 0',
                    },
                    class: "textColor",
                    on: {
                      click: (event) => {
                        this.editRateRule({ ruleInfo: { id: params.row.id, rule_state: 1 } }).then((res) => {
                          let { data, msg, scode, status } = res;
                          if (status === "ok") {
                            this.$YsMessage.success(data.message_text)
                            this.getHeiDuJianCe()
                          } else {
                            this.$YsMessage.error(msg);
                          }
                        })
                        event.stopPropagation();
                      },
                    },
                  }),
                  h("span", {
                    domProps: {
                      innerText: '编辑',
                    },
                    style: {
                      display: params.row.rule_state == 2 || params.row.rule_state == 1 ? "none" : "inline-block",
                      margin: "0 6px 0 0",
                    },
                    class: "textColor",
                    on: {
                      click: (event) => {
                        this.uploadFlag = true
                        this.exitTopTableItem(params.row)
                      },
                    },
                  }),
                  h("span", {
                    domProps: {
                      innerText: '删除',
                    },
                    style: {
                      display: params.row.rule_state == 1 ? "none" : "inline-block",
                    },
                    class: "textColor2",
                    on: {
                      click: (event) => {
                        this.handleDlelteItem(params.row);
                        event.stopPropagation();
                      },
                    },
                  }),
                  h("span", {
                    class: "textColor2",
                    style: {
                      display: params.row.rule_state == 1 ? "inline-block" : "none",
                    },
                  }, '--'),
                ]
              );
            },
          },
        ],
        data: [],
      },
      app_rule: {
        rule_name: [
          { required: true, message: "规则名称不能为空", trigger: "blur" },
        ],
        pixel: [
          { required: true, type: 'number', message: "像素距离不能为空", trigger: "blur" },
          { validator: validateStart, trigger: 'blur' },
        ],
        rule_file_name: [
          { required: true, validator: fileNameValidateStart },
        ]
      },
    };
  },

  methods: {
    ...mapActions(["setTempUploadDir", "getRuleBlackSubmitAPI", "getPageRateRule", "getPageEquMaterial", "getPageAllCraft", "getPageEquPart", "addRateRule", "editRateRule", "getZhwhRuleUse", "deleteRateRule", "setYuanTiaoruleCopy"]),

    //获取服务列表
    getHeiDuJianCe(val = '') {
      let _this = this;
      this.page.tableLoad = true;
      this.pege_param.keyword = val
      _this.getPageRateRule(this.pege_param).then((res) => {
        let { data, msg, scode, status } = res;
        _this.page.tableLoad = false;
        if (status === "ok") {
          this.page.data = data.ruleBeans;
          this.page.allTotal = data.all_recd;
        } else {
          _this.$YsMessage.error(msg);
          this.page.data = [];
          this.page.allTotal = 0;

        }
      }).catch((err) => {
        _this.page.tableLoad = false;
        _this.$YsMessage.error("获取数据失败");
      });
    },
    //分页
    onClickPage(pageNum) {
      this.pege_param.start_recd = pageNum;
      this.getHeiDuJianCe();
    },
    //选中行
    handleRowData(item) {
      this.$emit("setPigment", item)
    },
    //打开模态框
    openModal() {
      this.flawTypeflag = true
      this.uploadFlag = true
      this.$refs.heiduForm.resetFields()
      this.ruleInfo = this.$options.data().ruleInfo
      this.fileupload = this.$options.data().fileupload
      this.$refs.addqxgz.show()
    },
    //打开生效弹出
    setopenModal() {
      this.$emit('handleModal', true)
    },
    //确定
    handleOk(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.flawTypeflag) {
            this.addLeveltItem()
          } else {
            this.exitLeveltItem()
          }
        }
      });
    },
    //获取参数
    getParam() {
      let partInfo_array = []
      let materialInfo_array = []//材质集合
      let beans_array = []//材质集合
      this.ruleInfo.current_parts.map(v => { partInfo_array.push({ part_id: v }) })
      this.ruleInfo.current_materials.map(v => { materialInfo_array.push({ mat_id: v }) })
      this.ruleInfo.current_beans.map(v => { beans_array.push({ craft_id: v }) }) //焊接方式
      this.ruleInfo.rule_parts = partInfo_array
      this.ruleInfo.rule_materials = materialInfo_array
      this.ruleInfo.rule_craft_beans = beans_array
      this.ruleInfo.rule_type = this.rule_type
      this.fileSuccess = true
    },
    //综合评级新增
    async addLeveltItem() {
      let _this = this
      await _this.getParam()
      _this.addRateRule({ ruleInfo: this.ruleInfo, pre_version: "HD" }).then((res) => {
        let { data, msg, scode, status } = res;
        setTimeout(function () {
          _this.fileSuccess = false
        }, 500)
        if (status === "ok") {
          _this.$YsMessage.success(data.message_text)
          _this.$refs.addqxgz.close()
          _this.getHeiDuJianCe()
        } else {
          _this.$YsMessage.error(msg);
        }
      }).catch((err) => {
        this.fileSuccess = false
      });
    },
    //综合评级编辑
    async exitLeveltItem() {
      let _this = this
      await _this.getParam()
      _this.editRateRule({ ruleInfo: this.ruleInfo }).then((res) => {
        let { data, msg, scode, status } = res;
        this.fileSuccess = false
        if (status === "ok") {
          _this.$YsMessage.success(data.message_text)
          _this.$refs.addqxgz.close()
          _this.getHeiDuJianCe()
        } else {
          _this.$YsMessage.error(msg);
        }
      }).catch((err) => {
        this.fileSuccess = false
      });
    },
    //删除操作
    handleDlelteItem(item) {
      let _this = this;
      this.$YsModal.confirm({
        title: "删除",
        content: "<p>确认是否删除！</p>",
        onOk: () => {
          _this.deleteRateRule({ ruleInfo: { id: item.id } }).then((res) => {
            let { data, msg, scode, status } = res;
            if (status === "ok") {
              _this.$YsMessage.success("删除成功");
              _this.getHeiDuJianCe();
            } else {
              _this.$YsMessage.error(msg);
            }
          }).catch((err) => {
            _this.$YsMessage.error("删除失败");
          });
        },
      });
    },
    //取消
    handleCancel() {
      this.$refs.addqxgz.close()
      this.uploadFlag = false
    },

    //上传图片
    async uploadProcessThen(res, file) {
      this.fileupload.type = res.type; //上传类型
      this.fileupload.upload_name = res.name;
      this.fileSuccess = true
      let imgFolder = await this.setUpload();
      this.fileupload.upload_path = imgFolder.upload_path;
      this.fileupload.uploadpath = `${window.GlobalConfig.serviceProxy.BaseUrl}fileupload?uploadPath=${imgFolder.upload_path}`;
      this.$refs.upload.clearFiles();
    },
    //手动打开页面
    async setUpload() {
      let _this = this;
      return new Promise((resolve, reject) => {
        _this.setTempUploadDir().then((res) => {
          let { data, msg, scode, status } = res;
          if (data.upload_absolute_path && data.upload_path) {
            resolve(data);
          } else {
            reject(null);
          }
        });
      });
    },
    //上传文件成功
    handleSuccess(data, item) {
      this.ruleInfo.rule_file = `webDownLoad/${this.fileupload.upload_path}/${this.fileupload.upload_name}`;
      this.ruleInfo.rule_file_name = this.fileupload.upload_name
      this.$refs.heiduForm.validateField('rule_file_name');
      this.fileSuccess = false
      this.$YsMessage.success({
        content: "上传成功",
        duration: 5
      })
    },
    //格式
    handleFormatError(file) {
      this.$YsMessage.warning({
        duration: 4,
        closable: true,
        content:
          "文件 " + file.name + " 格式不正确，请上传 jpg 或 png 格式的图片。",
      });
    },
    //大小
    handleMaxSize(file) {
      this.$YsMessage.warning({
        duration: 4,
        closable: true,
        content: "文件 " + file.name + " 太大，不能超过 2M。",
      });
    },
    //提交
    setSubmitFn(item) {
      this.spinning = true
      this.getTimes(1000, true)
      this.getRuleBlackSubmitAPI({ ruleInfo: { id: item.id } }).then((res) => {
        let { data, msg, scode, status } = res;
        if (status === "ok") {
          this.getTimes(6, false)
          this.getHeiDuJianCe();
        } else {
          this.$YsMessage.error(msg);
          this.spinning = false
          clearInterval(this.clearTimer)
        }
      }).catch((err) => {
        this.$YsMessage.error(msg);
        this.spinning = false
        clearInterval(this.clearTimer)
      });
    },
    //设置加载时间
    getTimes(step, falg) {
      this.clearTimer = setInterval(() => {
        this.percent_val++
        if (falg && this.percent_val == 99) {
          this.percent_val = 98
        }
        if (this.percent_val >= 100) {
          this.spinning = false
          clearInterval(this.clearTimer - 1)
          clearInterval(this.clearTimer)
        }
      }, step);
    },
    //修改
    exitTopTableItem(item) {
      this.$refs.heiduForm.resetFields()
      this.flawTypeflag = false
      this.ruleInfo = {
        id: item.id,
        rule_type: this.rule_type,
        rule_name: item.rule_name,
        rule_version: item.rule_version,
        rule_file_name: item.rule_file_name,
        pixel: item.pixel,
        remark: item.remark,
        rule_parts: [],
        rule_materials: [],
        rule_craft_beans: [],
        current_parts: item.rule_parts ? item.rule_parts.map(v => v.part_id) : [],
        current_materials: item.rule_materials ? item.rule_materials.map(v => v.mat_id) : [], //备用属性
        current_beans: item.rule_craft_beans ? item.rule_craft_beans.map(v => v.craft_id) : [], //焊接方式集合
      }
      this.fileupload.upload_name = item.rule_file_name
      this.$refs.addqxgz.show()

    },
  },
  mounted() {
    this.getHeiDuJianCe();
  },
};
</script>
<style lang="less" scoped>
/deep/ .textColor {
  // color: '#0091FF';
  color: #0091ff;
  cursor: pointer;

  &:hover {
    // color: #0091ff;
    opacity: 0.8;
  }
}

/deep/ .textColor2 {
  color: #0091ff;
  // color: '#0091FF';
  cursor: pointer;

  &:hover {
    // color: #d53939;
    opacity: 0.8;
  }
}

.sub-out {
  height: 100% !important;
  border-radius: 4px 4px 0 0;
  position: relative;
  top: 0;

  .spin_x {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    // background: rgba(0, 0, 0, 0.2);
    justify-content: center;
    align-items: center;

    .progress {
      width: 30%;
    }
  }
}

/deep/ .hg100 {
  textarea {
    height: 100px;
  }
}

/deep/.shebeistyle {
  padding: 2px 10px;
  border-radius: 10px;
  color: #fff;
  background: rgba(0, 145, 255, 1);
}

.right-between {
  width: 80px;
  min-width: 80px;
  height: 40px;
  background: rgba(255, 255, 255, 0.39);
  border: 1px solid #0061ff;
  opacity: 1;
  border-radius: 4px;
  color: #0091ff;
  font-size: 16px;
  font-family: PingFang SC;
}

.searchBtn {
  width: 80px;
  min-width: 80px;
  height: 40px;
  font-family: PingFang SC;
}

.demo-upload-all {
  height: 48px;
  line-height: 48px;
  border: 1px solid #cfd7e5;
  border-radius: 4px;

  span {
    margin-left: 12px;
  }

  .demo-upload-add {
    position: absolute;
    right: 10px;
    top: 0;
  }
}

/deep/.ivu-upload-list {
  margin-top: 30px !important;

  li {
    padding: 0 !important;
    margin: 0 !important;
    height: 20px !important;
    // span{
    //   display: none !important;
    // }
  }

  .ivu-progress {

    .ivu-progress-text {
      color: #405580 !important;
      position: fixed !important;
      margin-top: -130px
    }
  }

}
</style>
